package cn.lf.android.lawfirm.worklog;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.List;

import cn.lf.android.lawfirm.BaseActivity;
import cn.lf.android.lawfirm.R;
import cn.lf.android.lawfirm.downloadcontroller.modle.Agreement;
import cn.lf.android.lawfirm.inputsource.TheSourcePeopleListActivity;
import cn.lf.android.lawfirm.inputsource.model.People;
import cn.lf.android.lawfirm.uploadcontroller.view.UpAgreementAdapter;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.utils.GetPathUtil;
import cn.lf.android.lawfirm.utils.timepicker.TimePicker;
import cn.lf.android.lawfirm.view.NoScrollListView;
import cn.lf.android.lawfirm.view.OptionDialog;
import cn.lf.android.lawfirm.worklog.controller.AddWorkLogConroller;
import cn.lf.android.lawfirm.worklog.controller.DeleteAgreementConroller;
import cn.lf.android.lawfirm.worklog.controller.WorkLogTypeConroller;
import cn.lf.android.lawfirm.worklog.molde.WorkLogType;

import static android.R.string.no;

public class AddWorkLogActivity extends BaseActivity implements WorkLogTypeConroller.WorkLogTypeCallback, AddWorkLogConroller.AddWorkLogCallback {

    /**
     * 返回
     **/
    private ImageButton img_left;
    /**
     * 标题
     **/
    private TextView mtitle;
    private EditText theme, content, worktime, waytime;
    private String caseID = "";
    private TextView adopt;
    private AutoRelativeLayout rl_logWorktype, rl_time, rl_tijiaochayue;
    private TextView tv_tijiaochayue, tv_time, logWorktype, tv_theme;
    private ImageView add_file;
    /**
     * 申请记录编号
     **/
    private TimePicker mTimePicker;
    private TimePicker mTimePicker_type;
    private List<WorkLogType> mList_type = new ArrayList<WorkLogType>();
    //--合同文件
    private List<Agreement> mListFileInfo = new ArrayList<Agreement>();
    private NoScrollListView file_list;
    private UpAgreementAdapter mAgreementAdapter;

    //--提交查閱人
    private People sourse_people;
    private String LogWorkType = "案件类";
    private List<String> mFilePath = new ArrayList<String>();//上传文件路径
    private WorkLogTypeConroller mWorkLogTypeConroller;
    private AddWorkLogConroller mAddWorkLogConroller;
    private String checkuserid = "";
    /**
     * 上传
     **/
    int SELECT = 1002;

    @Override
    public Object getContentResView() {
        return R.layout.activity_add_worklog;
    }

    @Override
    public void initView() {
        initTitle();
        caseID = getIntent().getStringExtra("caseID");
        theme = (EditText) findViewById(R.id.theme);
        content = (EditText) findViewById(R.id.content);
        worktime = (EditText) findViewById(R.id.worktime);
        waytime = (EditText) findViewById(R.id.waytime);
        add_file = (ImageView) findViewById(R.id.add_file);
        add_file.setOnClickListener(this);
        adopt = (TextView) findViewById(R.id.adopt);
        tv_tijiaochayue = (TextView) findViewById(R.id.tv_tijiaochayue);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_theme = (TextView) findViewById(R.id.tv_theme);
        logWorktype = (TextView) findViewById(R.id.logWorktype);
        rl_logWorktype = (AutoRelativeLayout) findViewById(R.id.rl_logWorktype);
        rl_logWorktype.setOnClickListener(this);
        rl_time = (AutoRelativeLayout) findViewById(R.id.rl_time);
        rl_time.setOnClickListener(this);
        rl_tijiaochayue = (AutoRelativeLayout) findViewById(R.id.rl_tijiaochayue);
        rl_tijiaochayue.setOnClickListener(this);
        adopt.setOnClickListener(this);
        file_list = (NoScrollListView) findViewById(R.id.file_list);
        mAgreementAdapter = new UpAgreementAdapter(AddWorkLogActivity.this, mListFileInfo, "工作日志添加");
        file_list.setAdapter(mAgreementAdapter);
    }


    private void initTitle() {
        img_left = (ImageButton) findViewById(R.id.img_left);
        img_left.setVisibility(View.VISIBLE);
        img_left.setOnClickListener(this);
        mtitle = (TextView) findViewById(R.id.eb_tv_title);
        mtitle.setVisibility(View.VISIBLE);
        mtitle.setText("工作日志添加");
    }

    @Override
    public void initData() {
        //滑动退出
//        addSwipeFinishLayout();
        mWorkLogTypeConroller = new WorkLogTypeConroller(this, this);
        mTimePicker = new TimePicker(this, 3,
                new TimePicker.OnPickerCallBack() {
                    @Override
                    public void pickerDone(String timeString, long timeInMillis) {
                        tv_time.setText(timeString);
                    }
                });
        mWorkLogTypeConroller.onWorkLogType();
        mAddWorkLogConroller = new AddWorkLogConroller(this, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_file://上传文件
                hintKbTwo();
                Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                intent1.setType("application/msword");
                if (Build.VERSION.SDK_INT >= 23) {// 判断版本
                    if (ContextCompat.checkSelfPermission(
                            AddWorkLogActivity.this,
                            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                            || ContextCompat.checkSelfPermission(mActivity,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat
                                .requestPermissions(
                                        AddWorkLogActivity.this,
                                        new String[]{
                                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                                Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                        8);
                    } else {
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                            startActivityForResult(intent1, SELECT);
                        } else {
                            startActivityForResult(intent1, SELECT);
                        }
                    }

                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        startActivityForResult(intent1, SELECT);
                    } else {
                        startActivityForResult(intent1, SELECT);
                    }
                }
                break;
            case R.id.rl_logWorktype://日志类型
                hintKbTwo();
                mTimePicker_type.show(getWindow().getDecorView());
                break;
            case R.id.rl_time://日期
                hintKbTwo();
                mTimePicker.show(getWindow().getDecorView());
                break;
            case R.id.rl_tijiaochayue://提交查阅
                hintKbTwo();
                Intent intent = new Intent(this, TheSourcePeopleListActivity.class);
                intent.putExtra("title", "提交查阅");
                intent.putExtra("isBusiness", "");
                startActivityForResult(intent, 1004);
                break;
            case R.id.adopt:
                hintKbTwo();
                if (check()) {
                    mAddWorkLogConroller.onAddWorkLog("", checkuserid, "0", "0", theme.getText().toString().trim(), tv_time.getText().toString(), worktime.getText().toString().trim(), "", waytime.getText().toString().trim(), "", "", LogWorkType, content.getText().toString(), "", "", mFilePath);
                }
                break;
            case R.id.img_left:
                hintKbTwo();
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        if (requestCode == 8) {// 读取文件
            if (grantResults[0] == 0) {// 允许
                Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                intent1.setType("application/msword");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    startActivityForResult(intent1, SELECT);
                } else {
                    startActivityForResult(intent1, SELECT);
                }
            } else {// 拒绝
//                if (!shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
//                        || !shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                giveUpShow("读取文件失败，请检查设备并开启权限");
//                }
            }
        }
    }

    public void doDelete(int position) {
        mFilePath.remove(position);
        mListFileInfo.remove(position);
        mAgreementAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1004://提交查閱
                    sourse_people = (People) data.getSerializableExtra("people");
                    tv_tijiaochayue.setText(sourse_people.userName);
                    checkuserid = sourse_people.userID;
                    break;
                default:
                    break;
            }
        }

        if (requestCode == SELECT) {// 相册选择完图片的回调
            if (resultCode == RESULT_OK && data != null) {
                Uri uri = data.getData();
                Agreement bean = new Agreement();
                bean.fileName = uri.getPath().toString();
                mFilePath.add(new GetPathUtil().getPath(this, uri));
                mListFileInfo.add(bean);
                mAgreementAdapter.notifyDataSetChanged();
            }
        }

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                Uri uri = data.getData();
                Agreement bean = new Agreement();
                bean.fileName = uri.getPath().toString();
                mFilePath.add(uri.getPath().toString());
                mListFileInfo.add(bean);
                mAgreementAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onWorkLogTypeSuccessed(List<WorkLogType> beans) {
        mList_type.addAll(beans);
        List<String> list_strs = new ArrayList<String>();
        for (WorkLogType workLogType : mList_type) {
            list_strs.add(workLogType.text);
        }
        mTimePicker_type = new TimePicker(this, 1, list_strs,
                new TimePicker.OnPickerCallBack() {
                    @Override
                    public void pickerDone(String timeString, long timeInMillis) {
                        logWorktype.setText(timeString);
                        LogWorkType = timeString;
                    }
                });
    }

    private boolean check() {
        if (theme.getText().toString().trim().length() == 0) {
            showCToast("请填写日志主题");
            return false;
        }
        if (logWorktype.getText().toString().trim().length() == 0) {
            showCToast("请填写日志类型");
            return false;
        }
        if (tv_time.getText().toString().trim().length() == 0) {
            showCToast("请填写日期");
            return false;
        }
        if (worktime.getText().toString().trim().length() == 0) {
            showCToast("请输入工作小时");
            return false;
        }
        if (waytime.getText().toString().trim().length() == 0) {
            showCToast("请输入在途小时");
            return false;
        }
        if (content.getText().toString().trim().length() == 0) {
            showCToast("请输入日志内容");
            return false;
        }
        if (tv_tijiaochayue.getText().toString().trim().length() == 0) {
            showCToast("请选择提交查阅");
            return false;
        }
        return true;
    }

    @Override
    public void onWorkLogTypetFailed() {

    }

    @Override
    public void onAddWorkLogSuccessed(String str) {
        WorkLogListActivity.isRefresh = true;
        showCToast("提交成功");
        finish();
    }

    @Override
    public void onAddWorkLogFailed() {

    }

    /**
     * 权限拒绝显示
     */
    private void giveUpShow(String str) {
        final OptionDialog dialog = new OptionDialog(this);
        dialog.setAnimationEnable(true);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_promess,
                null);
        TextView promess = (TextView) view.findViewById(R.id.promess);
        promess.setText(str);
        dialog.setPositiveListener("确定", new OptionDialog.OnPositiveListener() {
            @Override
            public void onClick(OptionDialog dialog) {
                dialog.optionDialogDismiss();
                dialog.dismiss();
            }
        });
        dialog.setCustomView(view);
        dialog.show();
    }
}
